package Binary;

import Hash.HashBuck;

public class BinarySearchTree {

    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        TreeNode cur = root;
        if(cur == null) {
            cur = new TreeNode(key);
        }
        TreeNode parent = null;
        while(cur != null) {
            parent = cur;
            if(cur.key > key) {
                cur = cur.left;
            } else if (cur.key < key) {
                cur = cur.right;
            } else {
                return false;
            }
        }
        TreeNode node = new TreeNode(key);
        if(parent.key > key) {
            parent.left = node;
        } else {
            parent.right = node;
        }
        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
        //遍历搜索树
        TreeNode cur = root;
        while(cur != null) {
            if(cur.key > key) {
                cur = cur.left;
            } else if (cur.key < key) {
                cur = cur.right;
            } else {
                return cur;
            }
        }
        return null;
    }
    //删除key的值
    public boolean remove(int key) {
        //找到key值的节点和父亲节点
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null) {
            parent = cur;
            if(key > cur.key) {
                cur = cur.right;
            } else if (key < cur.key) {
                cur = cur.left;
            } else {
                break;
            }
        }
        if (cur == null) {
            return false;
        }
        if (cur.left == null) {
            if(cur == root) {
                root = cur.right;
            } else if (cur == parent.left) {
                parent.left = cur.right;
            } else if (cur == parent.right) {
                parent.right = cur.right;
            }
        } else if (cur.right == null) {
            if(cur == root) {
                root = cur.left;
            } else if (cur == parent.left) {
                parent.left = cur.left;
            } else if (cur == parent.right) {
                parent.right = cur.left;
            }
        } else {
            //先要找到这颗子树中的最小值和他替换 然后删除(一直往左走就是最小
            //找出右子树中的最小值 这样子既比左大 又比右小
            TreeNode min = cur.right;
            TreeNode parentmin = null;
            while(min.left != null) {
                parentmin = min;
                min = min.left;
            }
            cur.key = min.key;
            if(min == parentmin.left) {
                parentmin.left = min.right;
            } else {
                parentmin.right = min.right;
            }
        }
        return true;
    }

}
